package com.itheima.consumer;

import com.itheima.pojo.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author 薛虎
 * @date 2021/1/22 10:30
 */
public class HttpCilent {

    public String post(String hostName, int port, Invocation invocation) throws IOException {

        //1.进行连接
        URL url = new URL("http", hostName, port, "/client");
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        //设置请求方式
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setDoOutput(true); //必须填

        //2.发送调用的信息
        OutputStream outputStream = httpURLConnection.getOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(invocation);
        oos.flush();
        oos.close();


        //3.将输入流转换成字符串,获取远程调用的结果
        InputStream inputStream = httpURLConnection.getInputStream();
        //将输入流转换成字符串
        return IOUtils.toString(inputStream);


    }

}
